package com.example.myapplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.security.SecureRandom;

public class CameraActivity extends AppCompatActivity {
    Bitmap bitmap;
    String imageName;
    String name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_camera);
        Intent intent=getIntent();
        Bundle bundle=intent.getExtras();
        name=bundle.getString("name");
        Log.d("zyy","previous name"+name);
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(takePictureIntent, 1);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            assert extras != null;
            Bitmap imageBitmap = (Bitmap) extras.get("data");

            // 从UUID中截取前三位数字

            SecureRandom random = new SecureRandom();
            String id = Integer.toString(random.nextInt(90000) + 10000); // 生成10000到99999之间的随机数
            // 将十六进制转换为十进制
            // 使用 imageBitmap 来显示图片或者保存到文件系统
            @SuppressLint("SdCardPath")
            File file=new File("/data/data/com.example.myapplication/",name+id+".png");

            try (FileOutputStream outputStream = new FileOutputStream(file)) {
                // 压缩 Bitmap 并将其写入文件
                imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                // 刷新输出流以确保所有数据都被写入
                outputStream.flush();
                bitmap = BitmapFactory.decodeStream(Files.newInputStream(file.toPath()));
                imageName=name+id+".png";
                Intent intent1=new Intent();
                intent1.putExtra("image",bitmap);
                intent1.putExtra("name",name);
                intent1.putExtra("imageName",imageName);
                setResult(Activity.RESULT_OK,intent1);
                finish();

            } catch (IOException e) {
                // 处理异常，例如打印日志或显示错误消息
                e.printStackTrace();
            }

        }

    }
}